<template>
	<view class="enhanced-map-container">
		<!-- 地图组件 -->
		<map 
			id="enhancedMap"
			:latitude="mapCenter.latitude" 
			:longitude="mapCenter.longitude" 
			:scale="mapScale"
			:markers="mapMarkers"
			:polyline="mapPolylines"
			:circles="mapCircles"
			:show-location="true"
			:enable-3D="true"
			:enable-zoom="true"
			:enable-scroll="true"
			:enable-rotate="false"
			:enable-overlooking="false"
			@tap="onMapTap"
			@markertap="onMarkerTap"
			@regionchange="onRegionChange"
			@updated="onMapUpdated"
			class="map-view">
		</map>
		
		<!-- 地图控制面板 -->
		<view class="map-control-panel">
			<!-- 定位按钮 -->
			<view class="control-btn location-btn" @click="locateUser" :class="{ 'loading': isLocating }">
				<image v-if="!isLocating" src="/static/index/定位2.png" mode="widthFix"></image>
				<view v-else class="loading-spinner"></view>
			</view>
			
			<!-- 路线规划按钮 -->
			<view class="control-btn route-btn" @click="toggleRoutePlanning" :class="{ 'active': showRoutePlanning }">
				<text>路线</text>
			</view>
			
			<!-- 清除按钮 -->
			<view class="control-btn clear-btn" @click="clearAll" v-if="hasContent">
				<text>清除</text>
			</view>
			
			<!-- 图层切换 -->
			<view class="control-btn layer-btn" @click="toggleMapLayer">
				<text>{{ currentLayer }}</text>
			</view>
		</view>
		
		<!-- 搜索框 -->
		<view class="search-container" v-if="showSearch">
			<input 
				class="search-input" 
				v-model="searchKeyword" 
				placeholder="搜索地点..."
				@confirm="searchLocation"
				@input="onSearchInput"
			/>
			<view class="search-results" v-if="searchResults.length > 0">
				<view 
					class="search-item" 
					v-for="(item, index) in searchResults" 
					:key="index"
					@click="selectSearchResult(item)"
				>
					<text class="item-name">{{ item.title }}</text>
					<text class="item-address">{{ item.address }}</text>
				</view>
			</view>
		</view>
		
		<!-- 信息窗口 -->
		<view class="info-window" v-if="selectedMarker" :style="infoWindowStyle">
			<view class="info-header">
				<text class="info-title">{{ selectedMarker.title }}</text>
				<view class="info-close" @click="closeInfoWindow">×</view>
			</view>
			<view class="info-content">
				<text class="info-address">{{ selectedMarker.address }}</text>
				<view class="info-actions" v-if="selectedMarker.type === 'store'">
					<button class="action-btn nav-btn" @click="navigateToMarker">导航</button>
					<button class="action-btn call-btn" @click="callMarker">联系</button>
				</view>
			</view>
		</view>
		
		<!-- 路线信息面板 -->
		<view class="route-info-panel" v-if="routeInfo">
			<view class="route-header">
				<text class="route-title">导航路线</text>
				<view class="route-close" @click="closeRouteInfo">×</view>
			</view>
			<view class="route-details">
				<view class="route-item">
					<text class="route-label">总距离:</text>
					<text class="route-value">{{ routeInfo.distance }}</text>
				</view>
				<view class="route-item">
					<text class="route-label">预计时间:</text>
					<text class="route-value">{{ routeInfo.duration }}</text>
				</view>
				<view class="route-item">
					<text class="route-label">路线类型:</text>
					<text class="route-value">{{ routeInfo.type }}</text>
				</view>
			</view>
			<view class="route-actions">
				<button class="route-action-btn" @click="startNavigation">开始导航</button>
				<button class="route-action-btn secondary" @click="shareRoute">分享路线</button>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-overlay" v-if="isLoading">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">{{ loadingText }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import tencentMapService from '@/utils/tencentMapService.js'
	
	export default {
		name: 'EnhancedMap',
		props: {
			// 初始中心点
			initialCenter: {
				type: Object,
				default: () => ({
					latitude: 34.83038,
					longitude: 113.56785
				})
			},
			// 初始缩放级别
			initialScale: {
				type: Number,
				default: 16
			},
			// 是否显示搜索框
			showSearch: {
				type: Boolean,
				default: true
			},
			// 是否允许路线规划
			allowRoutePlanning: {
				type: Boolean,
				default: true
			},
			// 目标位置
			targetLocation: {
				type: Object,
				default: null
			}
		},
		data() {
			return {
				mapContext: null,
				mapCenter: { ...this.initialCenter },
				mapScale: this.initialScale,
				mapMarkers: [],
				mapPolylines: [],
				mapCircles: [],
				
				// 用户位置
				userLocation: null,
				isLocating: false,
				
				// 路线规划
				showRoutePlanning: false,
				routeInfo: null,
				
				// 搜索功能
				searchKeyword: '',
				searchResults: [],
				searchTimeout: null,
				
				// 信息窗口
				selectedMarker: null,
				infoWindowStyle: {},
				
				// 地图图层
				currentLayer: '标准',
				mapLayers: ['标准', '卫星', '路况'],
				
				// 状态
				isLoading: false,
				loadingText: '加载中...',
				hasContent: false
			}
		},
		mounted() {
			this.initMap();
			this.getUserLocation();
		},
		methods: {
			// 初始化地图
			initMap() {
				this.mapContext = uni.createMapContext('enhancedMap', this);
				this.addInitialMarkers();
			},
			
			// 添加初始标记
			addInitialMarkers() {
				this.mapMarkers = [];
				
				// 添加用户位置标记
				if (this.userLocation) {
					this.addUserLocationMarker();
				}
				
				// 添加目标位置标记
				if (this.targetLocation) {
					this.addTargetLocationMarker();
				}
			},
			
			// 添加用户位置标记
			addUserLocationMarker() {
				if (!this.userLocation) return;
				
				this.mapMarkers.push({
					id: 'user_location',
					latitude: this.userLocation.latitude,
					longitude: this.userLocation.longitude,
					title: '我的位置',
					iconPath: '/static/index/定位2.png',
					width: 30,
					height: 30,
					callout: {
						content: '我的位置',
						color: '#333',
						fontSize: 12,
						borderRadius: 5,
						bgColor: '#fff',
						padding: 5,
						display: 'ALWAYS'
					}
				});
			},
			
			// 添加目标位置标记
			addTargetLocationMarker() {
				if (!this.targetLocation) return;
				
				this.mapMarkers.push({
					id: 'target_location',
					latitude: this.targetLocation.latitude,
					longitude: this.targetLocation.longitude,
					title: this.targetLocation.name || '目标位置',
					iconPath: '/static/vehicle_repair/storeDetails/banner.png',
					width: 40,
					height: 40,
					type: 'store',
					address: this.targetLocation.address || '',
					phone: this.targetLocation.phone || '',
					callout: {
						content: this.targetLocation.name || '目标位置',
						color: '#333',
						fontSize: 12,
						borderRadius: 5,
						bgColor: '#fff',
						padding: 5,
						display: 'ALWAYS'
					}
				});
			},
			
			// 获取用户位置
			getUserLocation() {
				this.isLocating = true;
				
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.userLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						
						// 更新地图中心
						this.mapCenter = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						
						// 添加用户位置标记
						this.addUserLocationMarker();
						
						this.isLocating = false;
						
						// 移动地图到用户位置
						if (this.mapContext) {
							this.mapContext.moveToLocation({
								latitude: res.latitude,
								longitude: res.longitude
							});
						}
					},
					fail: (err) => {
						console.error('获取位置失败:', err);
						this.isLocating = false;
						uni.showToast({
							title: '获取位置失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 定位用户
			locateUser() {
				this.getUserLocation();
			},
			
			// 切换路线规划
			toggleRoutePlanning() {
				this.showRoutePlanning = !this.showRoutePlanning;
				
				if (this.showRoutePlanning) {
					this.planRoute();
				} else {
					this.clearRoute();
				}
			},
			
			// 规划路线
			async planRoute() {
				if (!this.userLocation || !this.targetLocation) {
					uni.showToast({
						title: '缺少位置信息',
						icon: 'none'
					});
					return;
				}
				
				this.isLoading = true;
				this.loadingText = '规划路线中...';
				
				try {
					const from = {
						lat: this.userLocation.latitude,
						lng: this.userLocation.longitude
					};
					const to = {
						lat: this.targetLocation.latitude,
						lng: this.targetLocation.longitude
					};
					
					const routeResult = await tencentMapService.getRoute({
						from: from,
						to: to,
						mode: 'driving',
						policy: 'least_time'
					});
					
					this.routeInfo = {
						distance: routeResult.distance,
						duration: routeResult.duration,
						type: '驾车'
					};
					
					// 绘制路线
					this.drawRoute(routeResult);
					this.hasContent = true;
					
					uni.showToast({
						title: '路线规划成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('路线规划失败:', error);
					uni.showToast({
						title: error.message || '路线规划失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},
			
			// 绘制路线
			drawRoute(routeData) {
				if (routeData.polyline) {
					const points = tencentMapService.decodePolyline(routeData.polyline);
					
					this.mapPolylines = [{
						points: points,
						color: '#007aff',
						width: 4,
						dottedLine: false,
						arrowLine: true
					}];
				}
			},
			
			// 清除路线
			clearRoute() {
				this.mapPolylines = [];
				this.routeInfo = null;
				this.showRoutePlanning = false;
			},
			
			// 清除所有内容
			clearAll() {
				this.mapPolylines = [];
				this.mapCircles = [];
				this.routeInfo = null;
				this.showRoutePlanning = false;
				this.hasContent = false;
				this.selectedMarker = null;
			},
			
			// 切换地图图层
			toggleMapLayer() {
				const currentIndex = this.mapLayers.indexOf(this.currentLayer);
				const nextIndex = (currentIndex + 1) % this.mapLayers.length;
				this.currentLayer = this.mapLayers[nextIndex];
				
				// 这里可以根据需要实现图层切换逻辑
				uni.showToast({
					title: `切换到${this.currentLayer}图层`,
					icon: 'none'
				});
			},
			
			// 搜索地点
			async searchLocation() {
				if (!this.searchKeyword.trim()) return;
				
				this.isLoading = true;
				this.loadingText = '搜索中...';
				
				try {
					const results = await tencentMapService.searchNearby({
						location: this.mapCenter,
						keyword: this.searchKeyword,
						radius: 5000
					});
					
					this.searchResults = results.data.map(item => ({
						title: item.title,
						address: item.address,
						location: {
							latitude: item.location.lat,
							longitude: item.location.lng
						}
					}));
				} catch (error) {
					console.error('搜索失败:', error);
					uni.showToast({
						title: '搜索失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
				}
			},
			
			// 搜索输入处理
			onSearchInput() {
				// 防抖处理
				if (this.searchTimeout) {
					clearTimeout(this.searchTimeout);
				}
				
				this.searchTimeout = setTimeout(() => {
					if (this.searchKeyword.trim()) {
						this.searchLocation();
					} else {
						this.searchResults = [];
					}
				}, 500);
			},
			
			// 选择搜索结果
			selectSearchResult(item) {
				// 添加搜索结果的标记
				this.addSearchResultMarker(item);
				
				// 移动地图到搜索结果
				this.mapCenter = {
					latitude: item.location.latitude,
					longitude: item.location.longitude
				};
				
				if (this.mapContext) {
					this.mapContext.moveToLocation({
						latitude: item.location.latitude,
						longitude: item.location.longitude
					});
				}
				
				// 清空搜索
				this.searchKeyword = '';
				this.searchResults = [];
			},
			
			// 添加搜索结果标记
			addSearchResultMarker(item) {
				// 移除之前的搜索结果标记
				this.mapMarkers = this.mapMarkers.filter(marker => marker.id !== 'search_result');
				
				this.mapMarkers.push({
					id: 'search_result',
					latitude: item.location.latitude,
					longitude: item.location.longitude,
					title: item.title,
					iconPath: '/static/index/位置 拷贝 4.png',
					width: 35,
					height: 35,
					type: 'search',
					address: item.address,
					callout: {
						content: item.title,
						color: '#333',
						fontSize: 12,
						borderRadius: 5,
						bgColor: '#fff',
						padding: 5,
						display: 'ALWAYS'
					}
				});
			},
			
			// 地图点击事件
			onMapTap(e) {
				console.log('地图点击:', e);
				this.closeInfoWindow();
			},
			
			// 标记点击事件
			onMarkerTap(e) {
				const markerId = e.detail.markerId;
				const marker = this.mapMarkers.find(m => m.id === markerId);
				
				if (marker) {
					this.selectedMarker = marker;
					this.showInfoWindow(e.detail);
				}
			},
			
			// 显示信息窗口
			showInfoWindow(markerDetail) {
				// 这里可以根据标记位置计算信息窗口的显示位置
				this.infoWindowStyle = {
					position: 'absolute',
					top: '50%',
					left: '50%',
					transform: 'translate(-50%, -50%)',
					zIndex: 1000
				};
			},
			
			// 关闭信息窗口
			closeInfoWindow() {
				this.selectedMarker = null;
			},
			
			// 导航到标记
			navigateToMarker() {
				if (this.selectedMarker) {
					this.$emit('navigate', this.selectedMarker);
				}
			},
			
			// 联系标记
			callMarker() {
				if (this.selectedMarker && this.selectedMarker.phone) {
					uni.makePhoneCall({
						phoneNumber: this.selectedMarker.phone,
						success: () => {
							console.log('拨打电话成功');
						},
						fail: (err) => {
							console.error('拨打电话失败:', err);
						}
					});
				}
			},
			
			// 关闭路线信息
			closeRouteInfo() {
				this.routeInfo = null;
			},
			
			// 开始导航
			startNavigation() {
				this.$emit('startNavigation', this.routeInfo);
			},
			
			// 分享路线
			shareRoute() {
				this.$emit('shareRoute', this.routeInfo);
			},
			
			// 地图区域变化事件
			onRegionChange(e) {
				console.log('地图区域变化:', e);
			},
			
			// 地图更新事件
			onMapUpdated(e) {
				console.log('地图更新:', e);
			}
		}
	}
</script>

<style scoped>
	.enhanced-map-container {
		position: relative;
		width: 100%;
		height: 100%;
		overflow: hidden;
	}

	.map-view {
		width: 100%;
		height: 100%;
	}

	/* 地图控制面板 */
	.map-control-panel {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
		z-index: 1000;
	}

	.control-btn {
		width: 80rpx;
		height: 80rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
		backdrop-filter: blur(10rpx);
		font-size: 24rpx;
		font-weight: bold;
		color: #333;
	}

	.control-btn.active {
		background-color: rgba(0, 122, 255, 0.2);
		color: #007aff;
	}

	.control-btn.loading {
		background-color: rgba(0, 122, 255, 0.1);
	}

	.control-btn:active {
		background-color: rgba(0, 122, 255, 0.1);
	}

	.location-btn image {
		width: 40rpx;
		height: 40rpx;
	}

	.loading-spinner {
		width: 30rpx;
		height: 30rpx;
		border: 3rpx solid #f3f3f3;
		border-top: 3rpx solid #007aff;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}

	/* 搜索容器 */
	.search-container {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		right: 120rpx;
		z-index: 1000;
	}

	.search-input {
		width: 100%;
		height: 80rpx;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.15);
	}

	.search-results {
		background-color: white;
		border-radius: 8rpx;
		margin-top: 10rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		max-height: 400rpx;
		overflow-y: auto;
	}

	.search-item {
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
	}

	.search-item:last-child {
		border-bottom: none;
	}

	.item-name {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.item-address {
		font-size: 24rpx;
		color: #666;
	}

	/* 信息窗口 */
	.info-window {
		background-color: white;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
		min-width: 300rpx;
		max-width: 400rpx;
	}

	.info-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.info-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.info-close {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #999;
		border-radius: 50%;
		background-color: #f5f5f5;
	}

	.info-content {
		padding: 20rpx 30rpx 30rpx;
	}

	.info-address {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 20rpx;
	}

	.info-actions {
		display: flex;
		gap: 15rpx;
	}

	.action-btn {
		flex: 1;
		height: 70rpx;
		border: none;
		border-radius: 8rpx;
		font-size: 26rpx;
		font-weight: bold;
	}

	.nav-btn {
		background-color: #007aff;
		color: white;
	}

	.call-btn {
		background-color: #34c759;
		color: white;
	}

	/* 路线信息面板 */
	.route-info-panel {
		position: absolute;
		bottom: 20rpx;
		left: 20rpx;
		right: 20rpx;
		background-color: white;
		border-radius: 12rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
		z-index: 1001;
	}

	.route-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		border-bottom: 1rpx solid #eee;
	}

	.route-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.route-close {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #999;
		border-radius: 50%;
		background-color: #f5f5f5;
	}

	.route-details {
		padding: 20rpx 30rpx;
	}

	.route-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.route-label {
		font-size: 28rpx;
		color: #666;
	}

	.route-value {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.route-actions {
		display: flex;
		gap: 15rpx;
		padding: 20rpx 30rpx 30rpx;
	}

	.route-action-btn {
		flex: 1;
		height: 80rpx;
		border: none;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: bold;
		background-color: #007aff;
		color: white;
	}

	.route-action-btn.secondary {
		background-color: #f5f5f5;
		color: #666;
	}

	/* 加载状态 */
	.loading-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(255, 255, 255, 0.8);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
	}

	.loading-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	/* 响应式设计 */
	@media screen and (max-width: 750rpx) {
		.map-control-panel {
			right: 15rpx;
			top: 15rpx;
		}
		
		.control-btn {
			width: 70rpx;
			height: 70rpx;
			font-size: 22rpx;
		}
		
		.location-btn image {
			width: 35rpx;
			height: 35rpx;
		}
		
		.search-container {
			left: 15rpx;
			right: 100rpx;
		}
		
		.search-input {
			height: 70rpx;
			font-size: 26rpx;
		}
	}
</style>
